package com.yeban.javase.day16.classcreated;

import java.io.*;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/29
 */
public class Demo {

    public static void main(String[] args) {
        // 使用new创建
        Person person1 = new Person();

        // Object中的方法clone
        Person person2 = null;
        try {
            person2 = (Person) person1.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("clone创建：" + person2);

        // 序列化
        // 先序列化
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
            oos.writeObject(person1);
            System.out.println("对象已序列化写入文件。");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // ② 反序列化：从文件中读取对象
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
            Person person3 = (Person) ois.readObject();
            System.out.println("反序列化创建：" + person3);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 反射


        // 工厂模式


    }
}

class Person implements Cloneable, Serializable {
    private String name;
    private int age;

    public Person() {}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 实现clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}